<template>
  <v-content>
    <v-container>
      <v-snackbar
        v-model="snackbar"
      >
        {{ text }}
        <v-btn
          color="pink"
          text
          @click="snackbar = false"
        >
          Close
        </v-btn>
      </v-snackbar>
      <v-card
        class="overflow-hidden"
      >
        <v-toolbar
          flat
        >
          <v-icon>mdi-account</v-icon>
          <v-toolbar-title class="font-weight-light">{{this.$route.params.id}}</v-toolbar-title>
          <v-spacer></v-spacer>
        </v-toolbar>
        <v-card-text>
          <span class="subheading">Topic</span>
          <v-chip-group
            v-model="selection"
            :items="topics"
            active-class="text--accent-4"
            multiple
          >
            <v-chip v-for="topic in topics" :key="topic">{{topic}}</v-chip>
          </v-chip-group>
          <v-text-field
            :disabled="!isEditing"
            color="white"
            label="Title"
            :value="fileTitle"
          ></v-text-field>
          <v-text-field
            :disabled="!isEditing"
            color="white"
            label="Abstract"
            :value="fileAbstract"
          ></v-text-field>

          <v-row>
            <v-btn
              color="blue-grey"
              class="ma-2 white--text"
              @click="preview"
            >
              Preview
            </v-btn>
            <v-btn
              color="blue-grey"
              class="ma-2 white--text"
              @click="downLoad"
            >
              Download
            </v-btn>
            </v-row>

        </v-card-text>
      </v-card>
    </v-container>
    <v-container>
      <v-form>
        <v-card
          class="overflow-hidden"
          color="lighten-1"
        >
          <v-toolbar
            flat
            color="blue"
          >
            <v-toolbar-title class="font-weight-light">评审结果</v-toolbar-title>

            <v-spacer></v-spacer>
          </v-toolbar>
          <v-card-text>
            <v-autocomplete
              v-model="best"
              :items="marks"
              chips
              mandatory
              small-chips
              label="Mark"
            ></v-autocomplete>

            <v-textarea
              v-model="comment"
              label="comment"
              :rules="commentRule"
              auto-grow
              :value="comment"
            ></v-textarea>

            <v-autocomplete
              v-model="confidence"
              :items="levels"
              chips
              small-chips
              label="Confidence"
            ></v-autocomplete>
          </v-card-text>
          <v-divider></v-divider>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn
              v-if="this.$route.query.type===2"
              color="success"
              @click="changeSubmit"
            >
              Submit
            </v-btn>

            <v-btn
              v-else-if="this.$route.query.type===3"
              color="success"
              @click="changeSubmit"
            >
              Submit
            </v-btn>

            <v-btn
              v-else
              color="success"
              @click="submit"
            >
              Submit
            </v-btn>
          </v-card-actions>
          <v-snackbar
            v-model="hasSaved"
            :timeout="2000"
            absolute
            bottom
            left
          >
            {{text}}
          </v-snackbar>
        </v-card>
      </v-form>
      <side-bar></side-bar>
    </v-container>
  </v-content>
</template>

<script>
import pdfJS from 'pdfjs-dist'
import store from '../store'
import SideBar from './Components/SideBar'

export default {
  name: 'Review',
  components: {SideBar},
  data () {
    const generateFileTitle = _ => {
      console.log(this.$route.query.contributor)
      this.$axios.post('/getPaperInfo',
        {
          contributor: this.$route.query.contributor,
          fileTitle: this.$route.query.fileTitle
        })
        .then(resp => {
          console.log(resp.data)
          var response = resp.data
          this.meetingName = response.meetingFullName
          this.fileName = response.fileName
          this.fileTitle = response.fileTitle
          this.fileAbstract = response.fileAbstract
          this.id = response.id
          this.contributor = response.contributor
          this.topics = response.topics
        })
        .catch(error => {
          console.log(error)
        })
      return this.fileTitle
    }
    return {
      commentRule: [
        v => !!v || 'Comment Required',
        v => v.length <= 100 || 'Must be less than 10 characters'
      ],
      text: '',
      snackbar: false,
      hasSaved: false,
      isEditing: null,
      model: null,
      fileTitle: generateFileTitle(),
      fileName: '',
      fileAbstract: '',
      comment: '',
      meetingName: '',
      selection: [],
      topics: [],
      best: [1],
      marks: [-2, -1, 1, 2],
      confidence: [],
      levels: ['very low', 'low', 'high', 'very high']
    }
  },

  methods: {
    customFilter (item, queryText, itemText) {
      const textOne = item.name.toLowerCase()
      const textTwo = item.abbr.toLowerCase()
      const searchText = queryText.toLowerCase()

      return textOne.indexOf(searchText) > -1 ||
          textTwo.indexOf(searchText) > -1
    },
    preview () {
      this.$axios({
        headers: {
          'Content-Type': 'application/json'
        },
        url: '/download',
        method: 'post',
        // url for deploy
        data: '/usr/local/lab5/contribution/' + this.contributor + '_' + this.fileTitle + '_' + this.fileName,
        // url for local test
        // data: '/Users/wuyanjie/Desktop/' + this.contributor + '_' + this.fileTitle + '_' + this.fileName,
        // data: '/Users/yuzhexuan/' + this.contributor + '_' + this.fileTitle + '_' + this.fileName,
        responseType: 'blob'
      })
        .then((resp) => {
          if (resp.status === 200) {
            const binaryData = []
            binaryData.push(resp.data)
            let pdfUrl = window.URL.createObjectURL(new Blob(binaryData, {type: 'application/pdf'}))
            window.open(pdfUrl)
          } else {
            this.text ='下载文件失败'
            this.hasSaved = true
          }
        }) // 发送请求
    },
    downLoad () {
      this.$axios({
        headers: {
          'Content-Type': 'application/json'
        },
        url: '/download',
        method: 'post',
        // url for deploy
        data: '/usr/local/lab5/contribution/' + this.contributor + '_' + this.fileTitle + '_' + this.fileName,
        // url for local test
        // data: '/Users/wuyanjie/Desktop/' + this.contributor + '_' + this.fileTitle + '_' + this.fileName,
        // data: '/Users/yuzhexuan/' + this.contributor + '_' + this.fileTitle + '_' + this.fileName,
        responseType: 'blob'
      })
        .then((resp) => {
          if (resp.status === 200) {
            let blob = new Blob([resp.data], {type: 'application/pdf'})
            const elink = document.createElement('a')
            elink.download = this.fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
          } else {
            this.text ='下载文件失败'
            this.hasSaved = true
          }
        }) // 发送请求
    },
    submit () {
      this.isEditing = !this.isEditing
      this.$axios.post('/review', {
        meetingName: this.meetingName,
        contributor: this.contributor,
        title: this.fileTitle,
        pcMember: store.state.userName,
        mark: this.best,
        comment: this.comment,
        confidence: this.confidence
      })
        .then(resp => {
          if (resp.status === 200) {
            this.text = 'success'
            this.hasSaved = true
            this.$router.push('/reviewDashboard')
            location.reload()
          } else {
            this.text = 'review submit error'
            this.hasSaved = true
          }
        })
    },
    changeSubmit () {
      this.isEditing = !this.isEditing
      this.$axios.post('/changeReview', {
        meetingName: this.meetingName,
        contributor: this.contributor,
        title: this.fileTitle,
        pcMember: store.state.userName,
        mark: this.best,
        comment: this.comment,
        confidence: this.confidence
      })
        .then(resp => {
          console.log("true?"+resp.data)
          if (resp.status === 200 && resp.data === true) {
            this.text = 'success'
            this.hasSaved = true
            this.$router.push('/reviewDashboard')
            // location.reload()
          } else {
            this.text = '你还没发言'
            this.hasSaved = true
          }
        })
    },
    uploadFile () {
      let file = document.querySelector('input[type=file]').files[0]
      console.log(file.name)
      let reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        this.pdfData = atob(reader.result.substring(reader.result.indexOf(',') + 1))
        this.previewPDF()
      }
    },
    previewPDF () {
      // 引入pdf.js的字体
      let CMAP_URL = 'https://unpkg.com/pdfjs-dist@2.0.943/cmaps/'
      // 读取base64的pdf流文件
      let loadingTask = pdfJS.getDocument({
        data: this.pdfData, // PDF base64编码
        cMapUrl: CMAP_URL,
        cMapPacked: true
      })
      loadingTask.promise.then((pdf) => {
        this.loadFinished = true
        let numPages = pdf.numPages
        let pageNumber = 1
        this.getPage(pdf, pageNumber, numPages)
      })
    },
    getPage (pdf, pageNumber, numPages) {
      let _this = this
      pdf.getPage(pageNumber)
        .then((page) => {
          // 获取DOM中为预览PDF准备好的canvasDOM对象
          let canvas = this.$refs.myCanvas
          let viewport = page.getViewport(_this.scale)
          canvas.height = viewport.height
          canvas.width = viewport.width

          let ctx = canvas.getContext('2d')
          let renderContext = {
            canvasContext: ctx,
            viewport: viewport
          }
          page.render(renderContext)
            .then(() => {
              pageNumber += 1
              if (pageNumber <= 1) {
                _this.getPage(pdf, pageNumber, numPages)
              }
            })
        })
    }
  }
}
</script>
